import { useUserStore, useRouteStore } from '@/store';

export function createRouteGuard(router) {
  router.beforeEach(async (to, _, next) => {
    const location = await initRoutes(to);

    if (location) {
      next(location);
      return null;
    }

    const { isLogin } = useUserStore();
    const indexRouteName = 'index';
    const loginRouteName = 'login';
    const needLogin = !to.meta.constant;

    const routeSwitches = [
      // 如果登录时为登录路由，则切换到根页面
      { condition: isLogin && to.name === loginRouteName, callback: () => next({ name: indexRouteName }) },
      // 如果是常数路由，则允许直接访问
      { condition: !needLogin, callback: () => next() },
      // 如果路由需要登录，但用户没有登录，则切换到登录页面
      { condition: !isLogin && needLogin, callback: () => next({ name: loginRouteName }) },
      // 如果路由需要登录且用户已经登录，则允许访问
      { condition: isLogin && needLogin, callback: () => next() }
    ];

    routeSwitches.some(({ condition, callback }) => {
      if (condition) {
        callback();
      }
      return condition;
    });
  });
}

async function initRoutes(to) {
  const { isLogin } = useUserStore();

  const routeStore = useRouteStore();
  const isNotFoundRoute = to.name === 'not-found';

  // 初始化静态路由
  if (routeStore.isInitStaticRoute === false) {
    await routeStore.initStaticRoutes();

    // 解决刷新404错误
    if (isNotFoundRoute) {
      return { path: to.fullPath, query: to.query, replace: true, hash: to.hash };
    }
  }

  // 如果路由是常量路由，但不是“未找到”路由，则允许其访问。
  if (to.meta.constant && !isNotFoundRoute) {
    return null;
  }

  const isExist = routeStore.checkedRouteExist(to.path);
  if (isNotFoundRoute && !isExist) {
    return null;
  }

  if (isLogin === false) {
    return { path: '/login', replace: true };
  }

  await routeStore.initDynamicRoute(); // 初始化动态路由

  // 解决刷新404错误
  if (isNotFoundRoute) {
    const path = to.redirectedFrom?.name === 'index' ? '/' : to.fullPath;
    return { path, replace: true, query: to.query, hash: to.hash };
  }

  return null;
}
